/*
 * @lc app=leetcode.cn id=34 lang=cpp
 *
 * [34] 在排序数组中查找元素的第一个和最后一个位置
 */

// @lc code=start
#include <vector>
#include <iostream>
using namespace std;
class Solution
{
public:
    vector<int> searchRange(vector<int> &nums, int target)
    {
        int left = 0, right = nums.size() - 1;
        int mid = 0, first = -1, last = -1;
        while (left <= right) // 二分寻找左侧边界
        {
            mid = left + (right - left) / 2;
            if (nums[mid] > target)
            {
                right = mid - 1;
            }
            else if (nums[mid] < target)
            {
                left = mid + 1;
            }
            else if (nums[mid] == target)
            {
                right = mid - 1; // 右边界收缩
            }
        }
        if (left == nums.size() || nums[left] != target)// 判断是否越界或者没有目标值
        {
            return {first, last};
        }
        first = left;
        left = 0, right = nums.size() - 1;
        while (left <= right) // 二分寻找右侧边界
        {
            mid = left + (right - left) / 2;
            if (nums[mid] < target)
            {
                left = mid + 1;
            }
            else if (nums[mid] > target)
            {
                right = mid - 1;
            }
            else if (nums[mid] == target)
            {
                left = mid + 1; // 左边界收缩
            }
        }
        last = right;
        return {first, last};
    }
};
// @lc code=end
